
package com.danskin.wechat.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.danskin.wechat.api.client.DanskinCRMApiClient;
import com.danskin.wechat.api.client.WeiXinOpenApiClient;
import com.danskin.wechat.constant.DanskinConstants;
import com.danskin.wechat.dao.CrmBrandInfoDao;
import com.danskin.wechat.dao.CustCouponRecordDao;
import com.danskin.wechat.dao.CustInfoDao;
import com.danskin.wechat.dao.CustInfoExDao;
import com.danskin.wechat.dao.CustPointRecordDao;
import com.danskin.wechat.dao.WxCardConfigDao;
import com.danskin.wechat.dao.WxFansCardDao;
import com.danskin.wechat.dao.WxFansInfoDao;
import com.danskin.wechat.dto.CRMMemberRequest;
import com.danskin.wechat.dto.CustInfoDto;
import com.danskin.wechat.dto.SendCouponResultDto;
import com.danskin.wechat.entity.CrmBrandInfo;
import com.danskin.wechat.entity.CustCouponDetail;
import com.danskin.wechat.entity.CustCouponRecord;
import com.danskin.wechat.entity.CustInfo;
import com.danskin.wechat.entity.CustInfoEx;
import com.danskin.wechat.entity.CustInfoExView;
import com.danskin.wechat.entity.CustPointRecord;
import com.danskin.wechat.entity.WxCardConfig;
import com.danskin.wechat.entity.WxFansCard;
import com.danskin.wechat.entity.WxFansInfo;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.entity.example.CustInfoExExample;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.CustInfoService;
import com.danskin.wechat.service.SysAreaService;
import com.danskin.wechat.service.WechatMsgTemplateService;
import com.danskin.wechat.service.WechatOpService;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.util.StringUtil;
import com.danskin.wechat.util.VipLevelUtil;
import com.danskin.wechat.vo.CustInfoVo;

/***
 * 会员列表信息
 * 
 * @author admin
 *
 */
@Service
public class CustInfoServiceImpl extends BaseServiceImpl implements CustInfoService {

	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Autowired
	private CustInfoDao custInfoDao;

	@Autowired
	private CrmBrandInfoDao brandInfoDao;

	@Autowired
	private CustInfoExDao custInfoExDao;

	@Autowired
	private SysAreaService sysAreaService;

	@Autowired
	public WechatOpService wechatOpService;

	@Autowired
	private WxFansInfoDao wxFansInfoDao;

	@Autowired
	private WechatMsgTemplateService msgTemplateService;

	@Autowired
	private CustPointRecordDao custPointRecordDao;

	@Autowired
	private WxCardConfigDao wxCardConfigDao;

	@Autowired
	public CustCouponRecordDao custCouponDao;

	@Autowired
	private WxFansCardDao fansCardDao;

	@Autowired
	private TaskExecutor executor;

	@Override
	public AccessResponse<String> saveMemberRegister(Map<String, Object> map, WxMediaPlatform platForm, String memberId,
			String memberLevel) {
		// 2.处理用户信息
		// 根据手机号查询用户信息
		Integer custInfoId = 0;
		CustInfo custInfoParam = new CustInfo();
		custInfoParam.setMobile(map.get("mobile").toString());
		List<CustInfo> custInfoList = custInfoDao.selectCustInfoByExample(custInfoParam);
		if (CollectionUtils.isEmpty(custInfoList)) {
			// 封装用户信息用于新建用户
			custInfoParam = packageCustInfo(map, custInfoParam, memberId);
			// 新建用户返回用户主键ID
			custInfoDao.insertSelective(custInfoParam);
			custInfoId = custInfoParam.getId();
		} else {
			custInfoId = custInfoList.get(0).getId();
		}

		// 3.处理用户信息扩展表
		// 根据mpId和用户openId查询是否存在该用户扩展信息
		CustInfoEx custInfoExParam = new CustInfoEx();
		custInfoExParam.setMpId(platForm.getId());
		custInfoExParam.setCustId(custInfoId);
		List<CustInfoEx> custInfoExList = custInfoExDao.selectCustInfoExList(custInfoExParam);
		// 如果custInfoExList不为空，表示该用户已注册，否则创建用户扩展信息
		if (CollectionUtils.isNotEmpty(custInfoExList)) {
			return new AccessResponse<String>("-1", "该用户已注册，请勿重复操作");
		}
		// 封装用户扩展信息
		custInfoExParam = packageCustInfoEx(map, custInfoExParam, custInfoId, memberId, memberLevel);
		// 新建用户扩展信息
		custInfoExDao.insertSelective(custInfoExParam);
		int custInfoExId = custInfoExParam.getId();

		// 4.处理粉丝信息
		// 根据用户openId获取粉丝信息
		WxFansInfo fansInfo = wxFansInfoDao.selectByOpenId(null, map.get("openId").toString());
		if (fansInfo != null && fansInfo.getCustExId() == null) {
			fansInfo.setCustExId(custInfoExId);
			wxFansInfoDao.updateByPrimaryKeySelective(fansInfo);
		}

		return new AccessResponse<String>("0", "用户注册成功");
	}

	@Override
	public AccessResponse<String> pointChange(Map<String, Object> map, CrmBrandInfo brandInfo) {
		try {
			String wxOpenId = map.get("openId").toString();

			CustInfoExView custInfoDto = custInfoExDao.selectCustByOpenId(brandInfo.getMpId(), wxOpenId);
			// 封装用户扩展信息用于更新积分
			Integer integral = Integer.valueOf(map.get("integral") + "");
			Integer avaPoints = 0, totalPoints = 0, point = 0;
			CustInfoEx custInfoExParam = new CustInfoEx();
			custInfoExParam.setId(custInfoDto.getId());
			if (Integer.valueOf(map.get("addMinus") + "") == DanskinConstants.ADD_OR_MINUS_POINTS_ADD) { // 增加积分
				if (custInfoDto.getAvaPoints() == null || custInfoDto.getAvaPoints() == 0) { // 如果可用积分为null，直接赋值
					avaPoints = Integer.valueOf(map.get("integral") + "");
				} else { // 否则相加
					avaPoints = custInfoDto.getAvaPoints() + integral;
				}
				custInfoExParam.setAvaPoints(avaPoints);
				if (custInfoDto.getTotalPoints() == null || custInfoDto.getTotalPoints() == 0) { // 如果总积分为null，直接赋值
					totalPoints = integral;
				} else { // 否则相加
					totalPoints = custInfoDto.getTotalPoints() + integral;
				}
				custInfoExParam.setTotalPoints(totalPoints);
				point = integral;
			} else if (Integer.valueOf(map.get("addMinus") + "") == DanskinConstants.ADD_OR_MINUS_POINTS_MINUS) { // 扣除积分
				if (custInfoDto.getAvaPoints() == null || custInfoDto.getAvaPoints() < integral) { // 如果可用积分为null或者可用积分小于扣除积分，返回错误信息
					return new AccessResponse<String>("-1", "该用户可用积分不足");
				} else {// 否则相减
					avaPoints = custInfoDto.getAvaPoints() - integral;
					custInfoExParam.setAvaPoints(avaPoints);
				}
				totalPoints = custInfoDto.getTotalPoints();

				point = Integer.parseInt("-" + integral);
			}

			// 创建custPointRecord记录
			CustPointRecord custPointRecordParam = new CustPointRecord();
			custPointRecordParam.setCustExId(custInfoDto.getId());
			custPointRecordParam.setPoints(point);
			custPointRecordParam.setSource(map.get("activityName").toString());
			custPointRecordParam.setGetTime(new Date());
			custPointRecordParam.setExpiredTime(getNextYear());
			custPointRecordParam.setMemberId(custInfoDto.getMemberId());
			custPointRecordParam.setMobile(custInfoDto.getMobile());
			custPointRecordParam.setAvaPoints(avaPoints);
			custPointRecordParam.setTotalPoints(totalPoints);
			custPointRecordParam.setChangeId(StringUtil.getShortUUID());
			custPointRecordParam.setBrandId(brandInfo.getId());
			custPointRecordParam.setCreatedTime(new Date());

			// 调用crm接口
			DanskinCRMApiClient.createInstance().sendPointToCRM(custPointRecordParam.getChangeId(),
					custInfoDto.getMemberId(), custInfoDto.getMobile(), point, custPointRecordParam.getSource(),
					brandInfo.getBrandId());

			// 更新用户积分信息
			Integer updateCount = custInfoExDao.updateCustInfoEx(custInfoExParam);
			if (updateCount == null || updateCount == 0) {
				return new AccessResponse<String>("-1", "更新用户积分异常");
			}

			// 插入custPointRecord记录
			Integer insertCount = custPointRecordDao.insertCustPointRecord(custPointRecordParam);
			if (insertCount == null || insertCount == 0) {
				return new AccessResponse<String>("-1", "更新用户积分异常");
			}
			return new AccessResponse<String>("0", "更新用户积分成功", avaPoints.toString());
		} catch (Exception e) {
			LogUtil.error("=======积分变更异常", e);
			return new AccessResponse<String>("-1", "更新用户积分异常");
		}
	}

	@Override
	public AccessResponse<String> judgeUserStatusByTel(String mobile, Integer mpId) {
		try {
			// 数据校验
			if (StringUtils.isBlank(mobile)) {
				return new AccessResponse<String>("-1", "用户手机号为空");
			}
			if (mpId == null) {
				return new AccessResponse<String>("-1", "公众号mpId为空");
			}

			// 根据用户手机号和mpId查询用户custExId
			List<CustInfoDto> custInfoDtoList = custInfoDao.selectCustExIdByMobileAndOpenIdAndMpId(mobile, null, mpId);
			// 如果custExIdList为空，说明该用户不是会员
			if (CollectionUtils.isEmpty(custInfoDtoList)) {
				return new AccessResponse<String>("3", "该用户不是会员");
			}
			// 根据获取到的custExIdList查询是否是微信会员
			WxFansInfo param = new WxFansInfo();
			param.setCustExId(custInfoDtoList.get(0).getCustExId());
			Long fansCount = wxFansInfoDao.selectWxFansInfoCount(param);
			// 如果粉丝数为0，表示不是微信会员，返回该用户只是会员，不是微信会员
			if (fansCount == 0) {
				return new AccessResponse<String>("1", "该用户是会员，但不是微信会员");
			} else {
				return new AccessResponse<String>("2", "该用户是会员，也是微信会员");
			}
		} catch (Exception e) {
			LogUtil.error("=======根据手机号判断会员身份异常", e);
			return new AccessResponse<String>("-1", "系统异常");
		}
	}

	@Override
	public AccessResponse<String> judgeUserStatusByOpenId(String openId, Integer mpId) {
		try {
			// 数据验证
			if (StringUtils.isBlank(openId)) {
				return new AccessResponse<String>("-1", "用户openId为空");
			}
			if (mpId == null) {
				return new AccessResponse<String>("-1", "公众号mpId为空");
			}

			// 根据用户openId和公众号mpId查询符合条件的用户信息
			CustInfoEx custInfoExParam = new CustInfoEx();
			custInfoExParam.setWxOpenId(openId);
			custInfoExParam.setMpId(mpId);
			List<CustInfoEx> custInfoExList = custInfoExDao.selectCustInfoExList(custInfoExParam);
			// 如果custInfoExList为空，那么该用户不是会员
			if (CollectionUtils.isEmpty(custInfoExList)) {
				return new AccessResponse<String>("3", "该用户不是会员");
			}

			// 根据openId查询是否是微信会员
			WxFansInfo fansInfoParam = new WxFansInfo();
			fansInfoParam.setOpenId(openId);
			Long fansCount = wxFansInfoDao.selectWxFansInfoCount(fansInfoParam);
			// 如果粉丝数为0，表示不是微信会员，返回该用户只是会员，不是微信会员
			if (fansCount == 0) {
				return new AccessResponse<String>("1", "该用户是会员，但不是微信会员");
			} else {
				return new AccessResponse<String>("2", "该用户是会员，也是微信会员");
			}
		} catch (Exception e) {
			LogUtil.error("=======根据用户openId判断会员身份异常", e);
			return new AccessResponse<String>("-1", "系统异常");
		}
	}

	@Override
	public Object sendCouponByMobile(BigDecimal couponNum, String mobile, Integer mpId, String brandId,
			String changeReason) {
		// 数据校验
		if (StringUtils.isBlank(mobile)) {
			return new AccessResponse<String>("-1", "用户手机号为空");
		}
		if (mpId == null) {
			return new AccessResponse<String>("-1", "公众号mpId为空");
		}

		try {
			// 根据用户手机号和mpId查询用户信息
			List<CustInfoDto> custInfoDtoList = custInfoDao.selectCustExIdByMobileAndOpenIdAndMpId(mobile, null, mpId);
			// 如果custInfoDtoList为空，说明该用户不是会员
			if (CollectionUtils.isEmpty(custInfoDtoList)) {
				return new AccessResponse<String>("-1", "不存在该用户");
			}

			// 查询符合条件的优惠券配置
			WxCardConfig param = new WxCardConfig();
			param.setMpId(mpId);
			param.setCardType(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_CASH);
			param.setFaceValue(couponNum);
			List<WxCardConfig> cardConfigList = wxCardConfigDao.selectWxCardConfigList(param);
			if (CollectionUtils.isEmpty(cardConfigList)) {
				return new AccessResponse<String>("-1", "没有符合条件的现金优惠券");
			}

			// 执行CRM请求发券
			JSONObject jCRMCouponResult = DanskinCRMApiClient.createInstance().sendCouponToCRM(
					custInfoDtoList.get(0).getMemberId(), cardConfigList.get(0).getTemplateId(), 1, changeReason,
					brandId);

			if (jCRMCouponResult == null || !jCRMCouponResult.containsKey("status")
					|| jCRMCouponResult.getInteger("status") != 1) {
				return new AccessResponse<String>("-1", "请求CRM发券异常");
			} else {
				return new AccessResponse<SendCouponResultDto>("0", "发券成功", new SendCouponResultDto(
						jCRMCouponResult.getJSONArray("couponCodeJSONList"), cardConfigList.get(0).getName()));
			}
		} catch (Exception e) {
			LogUtil.error("======根据手机号发送现金券异常", e);
			return new AccessResponse<String>("-1", "系统异常");
		}
	}

	@Override
	public Object sendCouponToCust(String templateId, String mobile, String openId, Integer mpId, String brandId,
			String changeReason) {
		// 数据校验
		// if (StringUtils.isBlank(mobile)) {
		// return new AccessResponse<String>("-1", "用户手机号为空");
		// }
		if (mpId == null) {
			return new AccessResponse<String>("-1", "公众号mpId为空");
		}

		try {
			// 根据用户手机号和mpId查询用户信息
			List<CustInfoDto> custInfoDtoList = null;
			if (!StringUtil.isNullOrEmpty(mobile)) {
				custInfoDtoList = custInfoDao.selectCustExIdByMobileAndOpenIdAndMpId(mobile, null, mpId);
			} else {
				custInfoDtoList = custInfoDao.selectCustExIdByMobileAndOpenIdAndMpId(null, openId, mpId);
			}
			// 如果custInfoDtoList为空，说明该用户不是会员
			if (CollectionUtils.isEmpty(custInfoDtoList)) {
				return new AccessResponse<String>("-1", "不存在该用户");
			}

			// 查询符合条件的优惠券配置
			WxCardConfig param = new WxCardConfig();
			param.setMpId(mpId);
			// param.setCardType(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_CASH);
			// param.setFaceValue(couponNum);
			param.setTemplateId(templateId);
			List<WxCardConfig> cardConfigList = wxCardConfigDao.selectWxCardConfigList(param);
			if (CollectionUtils.isEmpty(cardConfigList)) {
				return new AccessResponse<String>("-1", "没有符合条件的优惠券");
			}
			WxCardConfig firstCardConfig = cardConfigList.get(0);
			if (firstCardConfig.getCardType() != null && (firstCardConfig.getCardType()
					.equals(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_CASH)
					|| firstCardConfig.getCardType().equals(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_DISCOUNT))) {

				// 执行CRM请求发券
				JSONObject jCRMCouponResult = DanskinCRMApiClient.createInstance().sendCouponToCRM(
						custInfoDtoList.get(0).getMemberId(), firstCardConfig.getTemplateId(), 1, changeReason,
						brandId);

				if (jCRMCouponResult == null || !jCRMCouponResult.containsKey("status")
						|| jCRMCouponResult.getInteger("status") != 1) {
					return new AccessResponse<String>("-1", "请求CRM发券异常");
				} else {
					return new AccessResponse<SendCouponResultDto>("0", "发券成功", new SendCouponResultDto(
							jCRMCouponResult.getJSONArray("couponCodeJSONList"), firstCardConfig.getName()));
				}
			} else {
				return new AccessResponse<String>("-1", "该优惠券无效。");
			}
		} catch (Exception e) {
			LogUtil.error("======根据手机号发送现金券异常", e);
			return new AccessResponse<String>("-1", "系统异常");
		}
	}

	@Override
	public Object sendCouponByOpenId(BigDecimal couponNum, String openId, Integer mpId, String brandId,
			String changeReason) {
		// 数据校验
		if (StringUtils.isBlank(openId)) {
			return new AccessResponse<String>("-1", "用户openId为空");
		}
		if (mpId == null) {
			return new AccessResponse<String>("-1", "公众号mpId为空");
		}

		try {
			// 根据用户手机号和mpId查询用户信息
			List<CustInfoDto> custInfoDtoList = custInfoDao.selectCustExIdByMobileAndOpenIdAndMpId(null, openId, mpId);
			// 如果custInfoDtoList为空，说明该用户不是会员
			if (CollectionUtils.isEmpty(custInfoDtoList)) {
				return new AccessResponse<String>("-1", "不存在该用户");
			}

			// 查询符合条件的优惠券配置
			WxCardConfig param = new WxCardConfig();
			param.setMpId(mpId);
			param.setCardType(DanskinConstants.WX_CARD_CONFIG_CARD_TYPE_CASH);
			param.setFaceValue(couponNum);
			List<WxCardConfig> cardConfigList = wxCardConfigDao.selectWxCardConfigList(param);
			if (CollectionUtils.isEmpty(cardConfigList)) {
				return new AccessResponse<String>("-1", "没有符合条件的现金优惠券");
			}

			// 执行CRM请求发券
			JSONObject jCRMCouponResult = DanskinCRMApiClient.createInstance().sendCouponToCRM(
					custInfoDtoList.get(0).getMemberId(), cardConfigList.get(0).getTemplateId(), 1, changeReason,
					brandId);

			if (jCRMCouponResult == null || !jCRMCouponResult.containsKey("status")
					|| jCRMCouponResult.getInteger("status") != 1) {
				return new AccessResponse<String>("-1", "请求CRM发券异常");
			} else {
				return new AccessResponse<SendCouponResultDto>("0", "发券成功", new SendCouponResultDto(
						jCRMCouponResult.getJSONArray("couponCodeJSONList"), cardConfigList.get(0).getName()));
			}
		} catch (Exception e) {
			LogUtil.error("======根据用户openId发送现金券异常", e);
			return new AccessResponse<String>("-1", "系统异常");
		}
	}

	@Override
	public List<CustInfoDto> selectCustExIdByMobileAndOpenIdAndMpId(String mobile, Integer mpId) {
		LogUtil.info("=======根据用户手机号和公众号mpId查询用户custExId参数：mobile=" + mobile + "&mpId=" + mpId);

		List<CustInfoDto> custInfoDtoList = new ArrayList<CustInfoDto>();

		try {
			custInfoDtoList = custInfoDao.selectCustExIdByMobileAndOpenIdAndMpId(mobile, null, mpId);
		} catch (Exception e) {
			LogUtil.error("=======根据用户手机号和公众号mpId查询用户custExId异常", e);
		}
		return custInfoDtoList;
	}

	@Override
	public CustInfo queryCustInfoById(Integer id) {
		LogUtil.info("======根据主键获取用户信息参数：id=" + id);

		CustInfo custInfo = new CustInfo();

		try {
			custInfo = custInfoDao.selectByPrimaryKey(id);
		} catch (Exception e) {
			LogUtil.error("======根据主键获取用户信息异常", e);
		}
		return custInfo;
	}

	@Override
	public List<CustInfo> selectCustInfoByExample(CustInfo param) {
		LogUtil.info("======查询符合条件的用户信息参数：" + ToStringBuilder.reflectionToString(param));

		List<CustInfo> custInfoList = new ArrayList<CustInfo>();

		try {
			custInfoList = custInfoDao.selectCustInfoByExample(param);
		} catch (Exception e) {
			LogUtil.error("=======查询符合条件的用户信息异常", e);
		}
		return custInfoList;
	}

	@Override
	public Integer selectCountByExample(CustInfo param) {
		LogUtil.info("======查询符合条件的用户数参数：" + ToStringBuilder.reflectionToString(param));

		Integer selectCount = 0;

		try {
			selectCount = custInfoDao.selectCountByExample(param);
		} catch (Exception e) {
			LogUtil.error("========查询符合条件的用户数异常", e);
		}
		return selectCount;
	}

	@Override
	public List<CustInfo> getCustInfoList(Page page) {
		// TODO Auto-generated method stub
		Map<String, Object> map = page.getMap();
		String title = (String) map.get("name");
		String newStartTime = (String) map.get("startTime");
		String newTime = (String) map.get("endTime");
		if (StringUtils.isNotEmpty(title)) {
			if (isNumeric(title)) {
				map.put("mobile", title);
			} else {
				map.put("nickName", title);
			}
		}
		if (StringUtils.isNotEmpty(newStartTime)) {
			map.put("newStartTime", newStartTime + " " + "00:00:01");
		}
		if (StringUtils.isNotEmpty(newTime)) {
			map.put("newTime", newTime + " " + "23:59:59");
		}
		return custInfoDao.listPageCustInfoList(page);
	}

	private boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	@Override
	public List<CustCouponDetail> getCustCouponDetailList(CustCouponDetail custCouponDetail) {
		// TODO Auto-generated method stub
		return custInfoDao.getCustCouponDetailList(custCouponDetail);
	}

	@Override
	public Map<String, Object> queryByOpenId(String wxOpenId) {
		Map<String, Object> map = custInfoDao.queryByOpenId(wxOpenId);
		return map;
	}

	@Override
	public CustInfoVo queryCustInfoDtoByOpenId(String wxOpenId) {
		LogUtil.info("========根据用户微信OpenId查询用户信息参数：wxOpenId=" + wxOpenId);

		CustInfoVo custInfoDto = new CustInfoVo();

		try {
			custInfoDto = custInfoDao.queryCustInfoDtoByOpenId(wxOpenId);
		} catch (Exception e) {
			LogUtil.error("=======根据用户微信OpenId查询用户信息异常", e);
		}
		return custInfoDto;
	}

	/**
	 * 保存或修改个人信息 新人礼专用
	 */
	@Override
	public CustInfo saveCustInfoSelective(CustInfo info, String openId) {
		Map<String, Object> map = custInfoDao.queryByOpenId(openId);
		int i = 0;
		CustInfo info2 = new CustInfo();
		if (StringUtils.isNotBlank(String.valueOf(map))) {
			info.setId(Integer.parseInt(String.valueOf(map.get("id"))));
			info.setMemberId(String.valueOf(map.get("member_id")));
			if (info.getBirthday() == null || StringUtils.isBlank(info.getName()) || info.getGender() == 0) {
				return null;
			} else {
				CrmBrandInfo brandInfo = brandInfoDao.selectByMpId((Integer) map.get("mpId"));
				i = custInfoDao.updateByPrimaryKeySelective(info);
				if (i > 0) {
					int id = info.getId();
					CustInfoEx infoEx = new CustInfoEx();
					infoEx.setVipLevel("v1");
					CustInfoExExample example = new CustInfoExExample();
					com.danskin.wechat.entity.example.CustInfoExExample.Criteria criteria = example.createCriteria();
					criteria.andWxOpenIdEqualTo(openId);
					int j = custInfoExDao.updateByExampleSelective(infoEx, example);
					if (j > 0) {
						info2 = custInfoDao.selectByPrimaryKey(id);
						CRMMemberRequest request = new CRMMemberRequest();
						request.setMemberId(info2.getMemberId());
						request.setBirthday(DateUtils.date2Str(info2.getBirthday()));
						String city=sysAreaService.getSysAreaByCode(info2.getCity());
						if(null!=city){
							request.setCity(info2.getCity());
						}else{
							request.setCity("");
						}
						String district=sysAreaService.getSysAreaByCode(info2.getDistrict());
						if(null!=district){
							request.setDistrict(info2.getDistrict());
						}else{
							request.setDistrict("");
						}
						String province=sysAreaService.getSysAreaByCode(info2.getProvince());
						if(null!=province){
							request.setProvince(info2.getProvince());
						}else{
							request.setProvince("");
						}
						request.setGender(String.valueOf(info2.getGender()));
						request.setMobile(info2.getMobile());
						request.setFullName(info2.getName());
						request.setMemberlevel("v1");
						request.setBrandId(brandInfo.getBrandId());
						request.setCardNum(String.valueOf(map.get("cardNo")));
						request.setHobby(info2.getHobby());
						request.setAddress(info2.getAddress());
						DanskinCRMApiClient danskinCRMApiClient = DanskinCRMApiClient.createInstance();
						danskinCRMApiClient.modifyMember(request);
						add("更新会员信息", "会员模块");
					}
				}
			}

		}
		return info2;
	}

	/**
	 * 激活会员卡
	 */
	@Override
	public void activateMemberInfo(String accessToken, int mpId, String appId, String mobile, String wxOpenId,
			String cardId, String userCardCode) {

		try {

			CrmBrandInfo brandInfo = brandInfoDao.selectByMpId(mpId);
			if (brandInfo != null) {
				CRMMemberRequest crmMember = new CRMMemberRequest();
				crmMember.setMobile(mobile);
				crmMember.setCardNum(mobile);
				crmMember.setBrandId(brandInfo.getBrandId());

				synchronized (this) {

					WxFansCard entity = new WxFansCard();
					entity.setMpId(mpId);
					entity.setOpenId(wxOpenId);
					entity.setWxCardId(cardId);
					entity.setUserCardCode(userCardCode);
					entity.setMembershipNumber(mobile);
					entity.setStatus((byte) 1);
					wechatOpService.saveFansCard(entity);

					JSONObject memberJson = DanskinCRMApiClient.createInstance().addMember(crmMember);
					// {"status":1,"errorMsg":"","member":{"memberId":"d51b2cdfa3b7440b905a774c5f13557b","memberLevel":"v0","cardNum":"15021311077","fullName":null,"idNum":null,"mobileNum":"15021311111","qqNum":null,"hobby":null,"address":null,"income":null,"job":null,"storeCode":null,"brand":"1"}}
					// {"status":2,"errorMsg":"手机号已存(会员已存在)","member":{"memberId":"7f58b7a706124f8e9460b6d80e35c25d","memberLevel":"v1","cardNum":"15021311077","fullName":"张三","idNum":null,"mobileNum":"15021311077","qqNum":null,"hobby":"football","address":null,"income":null,"job":null,"storeCode":null,"brand":"1"}}

					if (memberJson != null && memberJson.containsKey("status")) {

						int custAction = memberJson.getIntValue("status");// 1：代表会员注册；2：代表会员绑定
						if (custAction == 1 || custAction == 2) {

							JSONObject member = memberJson.getJSONObject("member");
							String memberId = member.getString("memberId");
							String memberLevel = member.getString("memberLevel");
							String fullName = member.getString("fullName");
							String idCardNo = member.getString("idNum");
							String province = member.getString("province");
							String city = member.getString("city");
							String address = member.getString("address");
							String gender = member.getString("gender");
							String birthday = member.getString("birthday");

							String qqNum = member.getString("qqNum");
							String hobby = member.getString("hobby");
							String income = member.getString("income");
							String job = member.getString("job");

							CustInfo custInfo = custInfoDao.selectByMemberId(memberId);
							if (custInfo == null) {
								custInfo = new CustInfo();
								custInfo.setName(fullName);
								custInfo.setMemberId(memberId);
								custInfo.setMobile(mobile);
								custInfo.setIdCardNo(idCardNo);
								custInfo.setProvince(province);
								custInfo.setCity(city);
								custInfo.setAddress(address);
								custInfo.setQq(qqNum);
								custInfo.setHobby(hobby);
								custInfo.setIncome(income);
								custInfo.setJob(job);
								if (!StringUtil.isNullOrEmpty(gender)) {
									custInfo.setGender(gender.equals("男") ? 1 : 2);
								} else {
									custInfo.setGender(0);
								}
								if (!StringUtil.isNullOrEmpty(birthday)) {
									custInfo.setBirthday(DateUtils.str2Date(birthday));
								}

								custInfo.setSource(0);
								custInfoDao.insertSelective(custInfo);
							}
							int custId = custInfo.getId();
							// 针对老会员
							// 判断openId是否绑定了另外一个手机号，及时切换到新的，旧的作废2017-12-03
							CustInfoEx custInfoExOld = custInfoExDao.queryByWxOpenId(wxOpenId);
							if (custInfoExOld != null && !custInfoExOld.getCustId().equals(custId)
									&& custInfoExOld.getWxOpenId().equals(wxOpenId)) {

								custInfoExOld.setWxOpenId("0");
								custInfoExOld.setLastModifiedTime(new Date());
								custInfoExDao.updateByPrimaryKeySelective2(custInfoExOld);
							}
							CustInfoEx custInfoEx = custInfoExDao.selectByCustId(mpId, custId);
							if (custInfoEx == null) {
								custInfoEx = new CustInfoEx();
								custInfoEx.setMpId(mpId);
								custInfoEx.setCustId(custId);
								custInfoEx.setMemberId(memberId);
								custInfoEx.setCardNo(mobile);
								custInfoEx.setVipLevel(memberLevel);
								custInfoEx.setWxOpenId(wxOpenId);
								Byte isGetGift = 0;
								if (!memberLevel.equalsIgnoreCase("v0")) {
									isGetGift = 1;
								}
								custInfoEx.setIsGetGift(isGetGift);

								custInfoExDao.insertSelective(custInfoEx);
							} else {
								custInfoEx.setCardNo(mobile);
								custInfoEx.setWxOpenId(wxOpenId);
								custInfoEx.setLastModifiedTime(new Date());
								custInfoExDao.updateByPrimaryKeySelective2(custInfoEx);
							}
							int custExId = custInfoEx.getId();

							// 激活会员卡
							int initPoints = custInfoEx.getAvaPoints() == null ? 0 : custInfoEx.getAvaPoints();
							int avaCouponNum = this.getCustAvaCouponNum(custExId);
							WeiXinOpenApiClient.createInstance().activateMemberCard(accessToken, cardId, userCardCode,
									mobile, initPoints, VipLevelUtil.getVipLevelName(memberLevel), avaCouponNum);

							// 保存粉丝信息，异步处理
							final String accessTokenF = accessToken;
							final String appIdF = appId;
							final String mobileF = mobile;
							final String wxOpenIdF = wxOpenId;
							final int custActionF = custAction;
							final CustInfoEx custInfoExF = custInfoEx;

							executor.execute(new Runnable() {

								@Override
								public void run() {
									WxFansInfo fansInfo = wechatOpService.saveFansInfo(accessTokenF,
											custInfoExF.getMpId(), wxOpenIdF, custInfoExF.getId());
									if (fansInfo != null) {
										if (custActionF == 1) { // 会员注册成功通知
											msgTemplateService.sendCustSignupMsg(accessTokenF, appIdF,
													custInfoExF.getWxOpenId(), fansInfo.getNickName(), mobileF,
													custInfoExF.getMemberId());

										} else if (custActionF == 2) { // 会员绑定成功通知
											msgTemplateService.sendCustBindMsg(accessTokenF, appIdF,
													custInfoExF.getWxOpenId(), fansInfo.getNickName(), mobileF);
										}
									}
								}
							});
						} else {
							LogUtil.error("调用CRM创建会员接口不允许重复调用。openId：" + wxOpenId + "，手机号码：" + mobile + "，UserCardCode："
									+ userCardCode);
						}
					} else {
						LogUtil.error("调用CRM创建会员接口失败。openId：" + wxOpenId + "，手机号码：" + mobile + "，UserCardCode："
								+ userCardCode);
					}

				}

			} else {
				LogUtil.error("找不到对应的品牌信息，公众号ID：" + mpId);
			}

		} catch (Exception e) {
			LogUtil.error("=======激活会员卡异常，openId：" + wxOpenId + "，手机号码：" + mobile + "，UserCardCode：" + userCardCode, e);
		}

	}

	@Override
	public void activateMemberInfo2(String accessToken, int mpId, String appId, String mobile, String wxOpenId,
			String cardId, String userCardCode) {

		try {

			CrmBrandInfo brandInfo = brandInfoDao.selectByMpId(mpId);
			if (brandInfo != null) {
				CRMMemberRequest crmMember = new CRMMemberRequest();
				crmMember.setMobile(mobile);
				crmMember.setCardNum(mobile);
				crmMember.setBrandId(brandInfo.getBrandId());

				synchronized (this) {

					WxFansCard entity = new WxFansCard();
					entity.setMpId(mpId);
					entity.setOpenId(wxOpenId);
					entity.setWxCardId(cardId);
					entity.setUserCardCode(userCardCode);
					entity.setMembershipNumber(mobile);
					entity.setStatus((byte) 1);
					wechatOpService.saveFansCard(entity);

					JSONObject memberJson = DanskinCRMApiClient.createInstance().addMember(crmMember);
					// {"status":1,"errorMsg":"","member":{"memberId":"d51b2cdfa3b7440b905a774c5f13557b","memberLevel":"v0","cardNum":"15021311077","fullName":null,"idNum":null,"mobileNum":"15021311111","qqNum":null,"hobby":null,"address":null,"income":null,"job":null,"storeCode":null,"brand":"1"}}
					// {"status":2,"errorMsg":"手机号已存(会员已存在)","member":{"memberId":"7f58b7a706124f8e9460b6d80e35c25d","memberLevel":"v1","cardNum":"15021311077","fullName":"张三","idNum":null,"mobileNum":"15021311077","qqNum":null,"hobby":"football","address":null,"income":null,"job":null,"storeCode":null,"brand":"1"}}

					if (memberJson != null && memberJson.containsKey("status")) {

						JSONObject member = memberJson.getJSONObject("member");
						String memberId = member.getString("memberId");
						String memberLevel = member.getString("memberLevel");
						String fullName = member.getString("fullName");
						String idCardNo = member.getString("idNum");
						String province = member.getString("province");
						String city = member.getString("city");
						String address = member.getString("address");
						String gender = member.getString("gender");
						String birthday = member.getString("birthday");

						String qqNum = member.getString("qqNum");
						String hobby = member.getString("hobby");
						String income = member.getString("income");
						String job = member.getString("job");

						CustInfo custInfo = custInfoDao.selectByMemberId(memberId);
						if (custInfo == null) {
							custInfo = new CustInfo();
							custInfo.setName(fullName);
							custInfo.setMemberId(memberId);
							custInfo.setMobile(mobile);
							custInfo.setIdCardNo(idCardNo);
							custInfo.setProvince(province);
							custInfo.setCity(city);
							custInfo.setAddress(address);
							custInfo.setQq(qqNum);
							custInfo.setHobby(hobby);
							custInfo.setIncome(income);
							custInfo.setJob(job);
							if (!StringUtil.isNullOrEmpty(gender)) {
								custInfo.setGender(gender.equals("男") ? 1 : 2);
							} else {
								custInfo.setGender(0);
							}
							if (!StringUtil.isNullOrEmpty(birthday)) {
								custInfo.setBirthday(DateUtils.str2Date(birthday));
							}

							custInfo.setSource(0);
							custInfoDao.insertSelective(custInfo);
						}
						// 针对老会员
						// 判断openId是否绑定了另外一个手机号，及时切换到新的，旧的作废2017-12-03
						CustInfoEx custInfoExOld = custInfoExDao.queryByWxOpenId(wxOpenId);
						if (custInfoExOld != null && custInfoExOld.getWxOpenId().equals(wxOpenId)) {
							custInfoExOld.setWxOpenId("0");
							custInfoExOld.setLastModifiedTime(new Date());
							custInfoExDao.updateByPrimaryKeySelective2(custInfoExOld);

						}
						int custId = custInfo.getId();
						CustInfoEx custInfoEx = custInfoExDao.selectByCustId(mpId, custId);
						if (custInfoEx == null) {
							custInfoEx = new CustInfoEx();
							custInfoEx.setMpId(mpId);
							custInfoEx.setCustId(custId);
							custInfoEx.setMemberId(memberId);
							custInfoEx.setCardNo(mobile);
							custInfoEx.setVipLevel(memberLevel);
							custInfoEx.setWxOpenId(wxOpenId);
							Byte isGetGift = 0;
							if (!memberLevel.equalsIgnoreCase("v0")) {
								isGetGift = 1;
							}
							custInfoEx.setIsGetGift(isGetGift);

							custInfoExDao.insertSelective(custInfoEx);
						} else {
							custInfoEx.setCardNo(mobile);
							custInfoEx.setWxOpenId(wxOpenId);
							custInfoEx.setLastModifiedTime(new Date());
							custInfoExDao.updateByPrimaryKeySelective2(custInfoEx);
						}
						int custExId = custInfoEx.getId();

						// 激活会员卡
						int initPoints = custInfoEx.getAvaPoints() == null ? 0 : custInfoEx.getAvaPoints();
						int avaCouponNum = this.getCustAvaCouponNum(custExId);
						WeiXinOpenApiClient.createInstance().activateMemberCard(accessToken, cardId, userCardCode,
								mobile, initPoints, VipLevelUtil.getVipLevelName(memberLevel), avaCouponNum);

						// 保存粉丝信息，异步处理
						final String accessTokenF = accessToken;
						final String wxOpenIdF = wxOpenId;
						final CustInfoEx custInfoExF = custInfoEx;

						executor.execute(new Runnable() {

							@Override
							public void run() {
								WxFansInfo fansInfo = wechatOpService.saveFansInfo(accessTokenF, custInfoExF.getMpId(),
										wxOpenIdF, custInfoExF.getId());
								if (fansInfo != null) {

								}
							}
						});

					} else {
						LogUtil.error("调用CRM创建会员接口失败。");
					}

				}

			} else {
				LogUtil.error("找不到对应的品牌信息，公众号ID：" + mpId);
			}

		} catch (Exception e) {
			LogUtil.error("=======激活会员卡异常", e);
		}

	}

	@Override
	public int updateMember(WxMediaPlatform mp, String openId, String mobile) {
		int i = 0;
		WxFansCard fansCard = fansCardDao.selectMemberCardIdByOpenId(mp.getId(), openId);
		if (fansCard != null) {

			WeiXinOpenApiClient.createInstance().activateMemberCard(mp.getAccessToken(), fansCard.getWxCardId(),
					fansCard.getUserCardCode(), mobile, null, null, null);

			fansCard.setMembershipNumber(mobile);
			i = fansCardDao.updateByPrimaryKeySelective(fansCard);
		}

		return i;
	}

	private int getCustAvaCouponNum(int custExId) {

		CustCouponRecord record = new CustCouponRecord();

		record.setCustExId(custExId);

		record.setIsUsed(0);

		record.setExpiredEndTime(new Date());

		return custCouponDao.selectAvaCouponByCondition(record);

	}

	@Override
	public int saveCustInfo(CustInfo custInfo2, CustInfoEx custInfoEx2) {
		CustInfo custInfo = custInfoDao.selectByMemberId(custInfo2.getMemberId());
		if (custInfo == null) {
			custInfo = custInfo2;

			custInfoDao.insertSelective(custInfo);
		}
		int custId = custInfo.getId();
		CustInfoEx custInfoEx = custInfoExDao.selectByCustId(custInfoEx2.getMpId(), custId);
		if (custInfoEx == null) {
			custInfoEx = new CustInfoEx();
			custInfoEx.setMpId(custInfoEx2.getMpId());
			custInfoEx.setCustId(custId);
			custInfoEx.setMemberId(custInfo2.getMemberId());
			custInfoEx.setVipLevel(custInfoEx2.getVipLevel());
			// custInfoEx.setCardNo(mobile);
			// custInfoEx.setVipLevel(memberLevel);
			// custInfoEx.setWxOpenId(wxOpenId);
			Byte isGetGift = 0;
			if (!custInfoEx2.getVipLevel().equalsIgnoreCase("v0")) {
				isGetGift = 1;
			}
			custInfoEx.setIsGetGift(isGetGift);
			// add("更新会员信息", "会员模块");
			return custInfoExDao.insertSelective(custInfoEx);
		} else {

			return -1;
		}
	}

	@Override
	public int createMemberInfo(CrmBrandInfo brandInfo, String mobile) {

		try {

			// CrmBrandInfo brandInfo = brandInfoDao.selectByBrandId(brandId);

			CRMMemberRequest crmMember = new CRMMemberRequest();
			crmMember.setMobile(mobile);
			crmMember.setCardNum(mobile);
			crmMember.setBrandId(brandInfo.getBrandId());

			JSONObject memberJson = DanskinCRMApiClient.createInstance().addMember(crmMember);
			if (memberJson != null && memberJson.containsKey("status")) {

				// int custAction = memberJson.getIntValue("status");//
				// 1：代表会员注册；2：代表会员绑定

				JSONObject member = memberJson.getJSONObject("member");
				String memberId = member.getString("memberId");
				String memberLevel = member.getString("memberLevel");
				String fullName = member.getString("fullName");
				String idCardNo = member.getString("idNum");
				String province = member.getString("province");
				String city = member.getString("city");
				String address = member.getString("address");
				String gender = member.getString("gender");
				String birthday = member.getString("birthday");

				String qqNum = member.getString("qqNum");
				String hobby = member.getString("hobby");
				String income = member.getString("income");
				String job = member.getString("job");
				synchronized (this) {

					CustInfo custInfo = custInfoDao.selectByMemberId(memberId);
					if (custInfo == null) {
						custInfo = new CustInfo();
						custInfo.setName(fullName);
						custInfo.setMemberId(memberId);
						custInfo.setMobile(mobile);
						custInfo.setIdCardNo(idCardNo);
						custInfo.setProvince(province);
						custInfo.setCity(city);
						custInfo.setAddress(address);
						custInfo.setQq(qqNum);
						custInfo.setHobby(hobby);
						custInfo.setIncome(income);
						custInfo.setJob(job);
						if (!StringUtil.isNullOrEmpty(gender)) {
							custInfo.setGender(gender.equals("男") ? 1 : 2);
						} else {
							custInfo.setGender(0);
						}
						if (!StringUtil.isNullOrEmpty(birthday)) {
							custInfo.setBirthday(DateUtils.str2Date(birthday));
						}

						custInfo.setSource(0);

						custInfoDao.insertSelective(custInfo);
					}
					int custId = custInfo.getId();
					CustInfoEx custInfoEx = custInfoExDao.selectByCustId(brandInfo.getMpId(), custId);
					if (custInfoEx == null) {
						custInfoEx = new CustInfoEx();
						custInfoEx.setMpId(brandInfo.getMpId());
						custInfoEx.setCustId(custId);
						custInfoEx.setMemberId(memberId);
						custInfoEx.setCardNo(mobile);
						custInfoEx.setVipLevel(memberLevel);
						// custInfoEx.setWxOpenId(wxOpenId);
						Byte isGetGift = 0;
						if (!memberLevel.equalsIgnoreCase("v0")) {
							isGetGift = 1;
						}
						custInfoEx.setIsGetGift(isGetGift);

						custInfoExDao.insertSelective(custInfoEx);
					}
					int custExId = custInfoEx.getId();

					return custExId;

				}
			} else {
				LogUtil.error("调用CRM创建会员接口失败。");
				return -1;
			}

		} catch (Exception e) {
			LogUtil.error("=======激活会员卡异常", e);
		}

		return 0;
	}

	@Override
	public int updateCustInfo(WxMediaPlatform mp, CustInfo custInfo2, CustInfoEx custInfoEx2) {

		CustInfo custInfo = custInfoDao.selectByMemberId(custInfo2.getMemberId());
		if (custInfo != null) {

			custInfo2.setId(custInfo.getId());
			custInfo2.setLastModifiedTime(new Date());
			custInfoDao.updateByPrimaryKeySelective(custInfo2);
			int custId = custInfo.getId();
			CustInfoEx custInfoEx = custInfoExDao.selectByCustId(custInfoEx2.getMpId(), custId);
			if (custInfoEx != null) {
				// custInfoEx.setVipLevel(custInfoEx2.getVipLevel());
				// custInfoEx.setTotalPoints(custInfoEx2.getTotalPoints());
				custInfoEx2.setId(custInfoEx.getId());
				custInfoEx2.setCardNo(custInfo2.getMobile());
				custInfoEx2.setLastModifiedTime(new Date());

				// addForApi(mp.getId(), "接口更新会员信息", "会员模块");
				int rows = custInfoExDao.updateByPrimaryKeySelective2(custInfoEx2);

				// 更新粉丝微信会员卡信息（会员卡号、积分、等级、优惠券）
				// int initPoints = custInfoEx.getAvaPoints() == null ? 0 :
				// custInfoEx.getAvaPoints();
				// int avaCouponNum =
				// this.getCustAvaCouponNum(custInfoEx.getId());
				if (rows > 0 && !StringUtil.isNullOrEmpty(custInfoEx.getWxOpenId())) {
					WxFansCard fansCard = fansCardDao.selectMemberCardIdByOpenId(mp.getId(), custInfoEx.getWxOpenId());
					if (fansCard != null) {

						WeiXinOpenApiClient.createInstance().activateMemberCard(mp.getAccessToken(),
								fansCard.getWxCardId(), fansCard.getUserCardCode(), custInfo2.getMobile(), null,
								VipLevelUtil.getVipLevelName(custInfoEx2.getVipLevel()), null);

						fansCard.setMembershipNumber(custInfo2.getMobile());
						fansCardDao.updateByPrimaryKeySelective(fansCard);
					}
				}
				return rows;
			}
		}
		return -1;
	}

	@Override
	public CustInfo updateCustInfoSelective(CustInfo info, String OpenId) {
		Map<String, Object> map = custInfoDao.queryByOpenId(OpenId);
		int i = 0;
		CustInfo info2 = new CustInfo();
		if (StringUtils.isNotBlank(String.valueOf(map))) {
			info.setId(Integer.parseInt(String.valueOf(map.get("id"))));
			info.setMemberId(String.valueOf(map.get("member_id")));

			CrmBrandInfo brandInfo = brandInfoDao.selectByMpId((Integer) map.get("mpId"));// 根据mpId获取
																							// 品牌
																							// 为后面
																							// 同步CRM
			i = custInfoDao.updateByPrimaryKeySelective(info);// 更新会员信息
			if (i > 0) {
				int id = info.getId();
				CustInfoEx infoEx = new CustInfoEx();

				if ("v0".equals(String.valueOf(map.get("vip")))) {
					if (info.getBirthday() == null || StringUtils.isBlank(info.getName()) || info.getGender() == null
							|| info.getGender() == 0) {
						infoEx.setVipLevel("v0");
					} else {
						infoEx.setVipLevel("v1");
					}
					CustInfoExExample example = new CustInfoExExample();
					com.danskin.wechat.entity.example.CustInfoExExample.Criteria criteria = example.createCriteria();
					criteria.andWxOpenIdEqualTo(OpenId);
					int j = custInfoExDao.updateByExampleSelective(infoEx, example);// 更新会员等级
				}

				info2 = custInfoDao.selectByPrimaryKey(id);
				CRMMemberRequest request = new CRMMemberRequest();
				if (null != info2.getVipLevel()) {
					request.setMemberlevel(infoEx.getVipLevel());
				}
				request.setMemberId(info2.getMemberId());
				request.setBirthday(DateUtils.date2Str(info2.getBirthday()));
				String city=sysAreaService.getSysAreaByCode(info2.getCity());
				if(null!=city){
					request.setCity(info2.getCity());
				}else{
					request.setCity("");
				}
				String district=sysAreaService.getSysAreaByCode(info2.getDistrict());
				if(null!=district){
					request.setDistrict(info2.getDistrict());
				}else{
					request.setDistrict("");
				}
				String province=sysAreaService.getSysAreaByCode(info2.getProvince());
				if(null!=province){
					request.setProvince(info2.getProvince());
				}else{
					request.setProvince("");
				}
				request.setGender(String.valueOf(info2.getGender()));
				request.setMobile(info2.getMobile());
				request.setFullName(info2.getName());
				request.setBrandId(brandInfo.getBrandId());
				request.setCardNum(String.valueOf(map.get("cardNo")));
				request.setHobby(info2.getHobby());
				request.setAddress(info2.getAddress());
				DanskinCRMApiClient danskinCRMApiClient = DanskinCRMApiClient.createInstance();
				danskinCRMApiClient.modifyMember(request);
			}
		}

		return info2;
	}

	@Override
	public Integer insertSelective(CustInfo param) {
		LogUtil.info("=======新建用户参数：" + ToStringBuilder.reflectionToString(param));
		Integer custInfoId = 0;
		try {
			custInfoDao.insertSelective(param);
			if (param.getId() != null) {
				custInfoId = param.getId();
			}
		} catch (Exception e) {
			LogUtil.error("=======新建用户异常", e);
		}
		return custInfoId;
	}

	@Override
	public void userViewCard(String accessToken, String openId, WxFansCard fansCard) {

		int avaPoints = 0;
		String vipLevel = "v0";
		int avaCouponNum = 0;

		CustInfoEx custInfo = custInfoExDao.selectByOpenId(openId);
		if (custInfo != null) {
			avaPoints = custInfo.getAvaPoints();
			vipLevel = custInfo.getVipLevel();
			// 获取可用券数量
			avaCouponNum = this.getCustAvaCouponNum(custInfo.getId());

		}

		WeiXinOpenApiClient.createInstance().updateUser(accessToken, fansCard.getWxCardId(), fansCard.getUserCardCode(),
				avaPoints, VipLevelUtil.getVipLevelName(vipLevel), avaCouponNum);
	}

	/**
	 * 封装用户扩展信息
	 * 
	 * @param map
	 * @param custInfoExParam
	 * @param custInfoId
	 * @param memberId
	 * @param memberLevel
	 * @return
	 * @author makunsmac
	 */
	private CustInfoEx packageCustInfoEx(Map<String, Object> map, CustInfoEx custInfoExParam, Integer custInfoId,
			String memberId, String memberLevel) {
		// 封装用户扩展信息
		custInfoExParam.setCustId(custInfoId);
		custInfoExParam.setMemberId(memberId);
		custInfoExParam.setCardNo(map.get("mobile").toString());
		custInfoExParam.setWxOpenId(map.get("openId").toString());
		custInfoExParam.setVipLevel(memberLevel);
		custInfoExParam.setAvaPoints(0);
		custInfoExParam.setTotalPoints(0);
		if (!StringUtils.equals(memberLevel, "v0")) {
			custInfoExParam.setIsGetGift((byte) 1);
		} else {
			custInfoExParam.setIsGetGift((byte) 0);
		}
		custInfoExParam.setCreatedTime(new Date());
		return custInfoExParam;
	}

	/**
	 * 封装用户信息
	 * 
	 * @param map
	 * @param memberId
	 * @return
	 * @author makunsmac
	 */
	private CustInfo packageCustInfo(Map<String, Object> map, CustInfo custInfoParam, String memberId) {
		custInfoParam.setMemberId(memberId);
		custInfoParam.setName(map.get("custName").toString());
		custInfoParam.setGender(Integer.valueOf(map.get("sex") + ""));
		try {
			custInfoParam.setBirthday(sdf.parse(map.get("birthday").toString()));
		} catch (ParseException e) {
			LogUtil.error("=======封装用户信息异常", e);
		}
		if (map.containsKey("address")) {
			custInfoParam.setAddress(map.get("address").toString());
		}
		if (map.containsKey("qq")) {
			custInfoParam.setQq(map.get("qq").toString());
		}
		if (map.containsKey("weibo")) {
			custInfoParam.setWeibo(map.get("weibo").toString());
		}
		if (map.containsKey("hobby")) {
			custInfoParam.setHobby(map.get("hobby").toString());
		}
		custInfoParam.setSource(DanskinConstants.CUST_INFO_SOURCE_WECHAT);
		return custInfoParam;
	}

	/**
	 * 封装粉丝信息
	 * 
	 * @param param
	 * @param fansInfoJSON
	 * @return
	 * @author makunsmac
	 */
	private WxFansInfo packageFansInfo(WxFansInfo param, JSONObject fansInfoJSON) {
		param.setUnionId(fansInfoJSON.getString("unionid"));
		param.setOpenId(fansInfoJSON.getString("openid"));
		param.setNickName(fansInfoJSON.getString("nickname"));
		param.setHeadImgUrl(fansInfoJSON.getString("headimgurl"));
		param.setGender(fansInfoJSON.getInteger("sex"));
		param.setCity(fansInfoJSON.getString("city"));
		param.setProvince(fansInfoJSON.getString("province"));
		param.setCountry(fansInfoJSON.getString("country"));
		param.setLanguage(fansInfoJSON.getString("language"));
		param.setSubscribe(fansInfoJSON.getInteger("subscribe"));
		param.setSubscribeTime(fansInfoJSON.getDate("subscribe_time"));
		param.setRemark(fansInfoJSON.getString("remark"));
		param.setGroupId(fansInfoJSON.getInteger("groupid"));
		param.setTagidList(fansInfoJSON.getString("tagid_list"));
		return param;
	}

	private static Date getNextYear() {
		Calendar ca = Calendar.getInstance();
		ca.setTime(new Date());
		ca.add(Calendar.YEAR, 1);
		ca.set(Calendar.MONTH, 12);
		ca.set(Calendar.DATE, 31);
		return ca.getTime();
	}

	@Override
	public List<CustInfo> getCustInfoListExport(String name, String mobile, String subscribe, String startTime,
			String endTime, String mpId) {
		// TODO Auto-generated method stub
		if (StringUtils.isNotEmpty(startTime)) {
			startTime = startTime + " " + "00:00:01";
		} else {
			startTime = DateUtils.getStartTime() + " " + "00:00:01";
		}
		if (StringUtils.isNotEmpty(endTime)) {
			endTime = endTime + " " + "23:59:59";
		} else {
			endTime = DateUtils.getEndTime() + " " + "23:59:59";
		}
		return custInfoDao.getCustInfoListExport(name, mobile, subscribe, startTime, endTime, mpId);
	}

	@Override
	public Map<String, Object> queryCustVipLevel(String openId) {

		return custInfoExDao.queryCustVipLevel(openId);
	}
}
